<?php

namespace App\Exceptions;

use App\Http\Common\Utils\Helper;
use App\Http\Common\Utils\ReturnData;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    public function render($request, Throwable $e)
    {

        if ($e instanceof HttpException) {
            $code = method_exists($e,'getStatusCode')?$e->getStatusCode():$e->getCode();
            if (view()->exists('errors.' . $code)) {
                $message  = $e->getMessage();
                return response()->view('errors.' . $e->getStatusCode(), ['message'=>$message], $e->getStatusCode());
            }
        }


        if ($e instanceof \Exception && Helper::isAjaxRequest()) {
            $code = method_exists($e,'getStatusCode')?$e->getStatusCode():$e->getCode();
            $message  = $e->getMessage();
            return response()->json(ReturnData::create($code,'null',$message));
        }

        if ($e instanceof \Exception) {
            $code = method_exists($e,'getStatusCode')?$e->getStatusCode():$e->getCode();
            $message  = $e->getMessage();
            if($code == 404){
                $message = '页面不存在';
            }

            return response()->view('admin/admin/error404',['message'=>$message,'code'=>$code]);
        }

        return parent::render($request, $e);
    }
}
